// 我的文章页面服务逻辑

import type { Article, ArticleStats } from './types'

const API_BASE_URL = 'http://localhost:3000/api'

// 获取我的文章列表
export const fetchMyArticles = async (): Promise<Article[]> => {
  const token = localStorage.getItem('token')
  const res = await fetch(`${API_BASE_URL}/articles/my-articles`, {
    headers: token ? { Authorization: `Bearer ${token}` } : {}
  })

  if (res.ok) {
    return await res.json()
  }

  return []
}

// 删除文章
export const deleteArticle = async (id: number): Promise<void> => {
  const token = localStorage.getItem('token')
  const res = await fetch(`${API_BASE_URL}/articles/${id}`, {
    method: 'DELETE',
    headers: { Authorization: `Bearer ${token}` }
  })

  if (!res.ok) {
    const err = await res.json()
    throw new Error(err.message || '删除失败')
  }
}

// 获取文章统计
export const fetchArticleStats = async (): Promise<ArticleStats> => {
  const token = localStorage.getItem('token')
  const res = await fetch(`${API_BASE_URL}/articles/my-stats`, {
    headers: token ? { Authorization: `Bearer ${token}` } : {}
  })

  if (res.ok) {
    return await res.json()
  }

  return {
    totalArticles: 0,
    totalViews: 0,
    totalLikes: 0
  }
}

// 格式化日期
export const formatDate = (dateString: string | undefined): string => {
  if (!dateString) return '未知日期'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
} 